const config = require("../config.js");
let cache = {};//在用户拒绝授权后，保存当前请求信息，用于下次请求
let baseUrl = "http://hq.c2c.com/v1/";//请求根地址



function setBaseUrl(url) {
    baseUrl = url;
}


function toPromise(fn, config) {
    return new Promise((resolve, reject) => {
        config = config || {}
        config.success = res => {
            resolve(res)
        }
        config.fail = res => {
            reject(res)
        }
        fn(config)
    })
}

function wxLogin() {
    return new Promise((resolve, reject) => {
        console.log('【wx.login】');
        wx.login({
            success: function (res) {
                console.log('【wx.login】success');
                resolve(res);
            },
            fail: function () {
                console.warn("【wx.login】fail");
                reject();
            }
        })
    });
}



function openSetting() {
    return new Promise((resolve, reject) => {
        wx.openSetting({
            success(res) {
                if (res.authSetting['scope.userInfo'] === true) {
                    resolve();
                } else {
                    reject();
                }
            },
            fail() {
                reject();
            }
        })
    })
}


function wxGetUserInfo(loginInfo) {
    return new Promise((resolve, reject) => {
        console.log('【wx.getUserInfo】');
        wx.getUserInfo({
            success: function (res) {
                console.log("【wx.getUserInfo】success");
                wx.setStorageSync('user', res.userInfo);
                resolve({ loginInfo, userInfo: res });
            },
            fail: function (res) {
                console.warn("【wx.getUserInfo】fail")
                // reject(res);
                toPromise(wx.showModal, {
                    title: "提示",
                    showCancel: false,
                    content: '请您允许授权呢称和头像信息,并在接下来的提示中勾选用户信息并点击确定,谢谢！',
                }).then(openSetting).then(s => {
                    wxLogin().then(a => {
                        wxGetUserInfo(a).then(b => {
                            resolve(b);
                        });
                    });
                }).catch(err => {
                    wx.switchTab({
                        url: '/pages/home/home',
                    });
                })
            },
        })
    });
}


function login(data) {
    return new Promise((resolve, reject) => {

        wx.request({
            url: baseUrl + config.login.url,
            data: {},
            method: 'GET',
            header: { 'Code': data.loginInfo.code, 'Encrypted-Data': data.userInfo.encryptedData, 'IV': data.userInfo.iv },
            success: function (res) {
                if (res.data.status.code === 2000) {
                    wx.setStorage({
                        key: 'sid',
                        data: res.data.data.sid
                    })
                    resolve()
                } else {
                    reject(res.data.status)
                }

            },
            fail: function (res) {
                reject(res)
            },
        })
    });
}



var tid = 0
function doRequest(url, config) {
    return new Promise((resolve, reject) => {
        wx.request({
            url: baseUrl + url,
            data: config.data,
            method: config.method,
            header: config.header,
            success: function (res) {
                try {
                    let code = res.data.status.code;
                    if (code === 2000) {
                        resolve(res.data)
                    } else {
                        if (code === 40001) {
                            //login timeout
                            //relogin after 1s
                            clearTimeout(tid)
                            tid = setTimeout(function () {
                                wx.removeStorage({
                                    key: 'sid',
                                    success: function (res) { },
                                })
                                resolve(request(url, config))
                            }, 1000)

                        } else {
                            reject(res.data.status);
                        }
                    }
                } catch (err) {
                    reject({ message: "服务器错误" });
                }

            },
            fail: function (res) {
                reject(res)
            }
        })
    });
}



function request(url, config) {
    cache = { url, config };
    return new Promise((resolve, reject) => {
        let cfg = { login: true, data: {}, header: {}, base: true }
        for (var k in config) {
            cfg[k] = config[k];
        }

        if (cfg.login === true) {
            //if need login
            // get sid from storage
            toPromise(wx.getStorage, { key: "sid" }).then(res => {
                //do request
                cfg.header.sid = res.data;
                resolve(doRequest(url, cfg));
            }).catch(err => {
                //fail to get sid
                //do login
                wxLogin().then(wxGetUserInfo).then(login).then(res => {
                    wx.getStorage({
                        key: 'sid',
                        success: function (res) {
                            cfg.header.sid = res.data;
                            resolve(doRequest(url, cfg));
                        },
                    })
                }).catch(err => {
                    reject(err)
                })
            })
            return
        }
        return resolve(doRequest(url, cfg))
    })
}


module.exports = {
    get: function (url, config) {
        let cfg = config || {};
        cfg.method = "GET";
        return request(url, cfg)
    },
    post: function (url, config) {
        let cfg = config || {};
        cfg.method = "POST";
        return request(url, cfg)
    },
    setBaseUrl
}